﻿using System;
using RayDen.Library.Core.Primitives;

namespace RayDen.RayEngine.Core.Types.Volume {
    public class VolumeComputation {
        public
            VolumeComputation(VolumeIntegrator vol) {
            float maxRayLen = vol.GetMaxRayLength();
            var maxSampleCount = (int)Math.Round(maxRayLen / vol.GetStepSize()) + 1;

            Rays = new RayData[maxSampleCount];
            CurrentRayIndex = new int[maxSampleCount];
            ScatteredLight = new RgbSpectrum[maxSampleCount];

            Reset();
        }

        public void AddRays(RayBuffer rayBuffer) {
            for (var i = 0; i < RayCount; ++i)
                CurrentRayIndex[i] = rayBuffer.AddRay(ref Rays[i]);
        }

        public RgbSpectrum CollectResults(RayBuffer rayBuffer) {
            // Add scattered light
            var radiance = new RgbSpectrum();
            for (var i = 0; i < RayCount; ++i) {
                var h = rayBuffer.rayHits[CurrentRayIndex[i]];
                if (h.Index == RayBuffer.NotHit) {
                    // The light source is visible, add scattered light
                    radiance += ScatteredLight[i];//*MathLab.Exp(-h.Distance)
                }
            }

            return radiance;
        }

        public int GetRayCount() { return RayCount; }
        public RgbSpectrum GetEmittedLight() { return EmittedLight; }


        public void Reset() {
            RayCount = 0;
            EmittedLight = new RgbSpectrum();
        }

        public int RayCount;
        public RayData[] Rays;
        public int[] CurrentRayIndex;
        public RgbSpectrum[] ScatteredLight;
        public RgbSpectrum EmittedLight;

    };
}
